Skip to content

Code generation for ThingClient subclasses - #89

Draft
rwb27 wants to merge 20 commits into
mainfrom
client-code-generation
Draft

rwb27 wants to merge 20 commits into
mainfrom
client-code-generation

Conversation

@rwb27

@rwb27 rwb27 commented Dec 4, 2024 •

Copy link
Copy Markdown
Collaborator

Currently, ThingClient subclasses are generated on-the-fly from a Thing Description. This "gets the job done" and means it's always possible to have a client that's up to date with the server. However, it would be nice to support static analysis, e.g. type checking, autocompletion, etc. with importable client classes for specific instruments.

Functionality

This PR implements client code generation, specifically:

  • A client class is created, subclassing ThingClient and named as per the title of the Thing Description.
  • Properties are added using their names from the TD
    • Property types are converted to Python type hints (with very basic conversion)
    • Read-only properties are made read-only. Write-only properties still have a read method.
    • Implementations use get_property, set_property as provided by ThingClient
  • Actions are added using names from the TD
    • The input schema is broken down into its properties (i.e. arguments), and each property's schema is converted to an argument with a type hint and default.
    • Required properties of the input schema become required arguments
    • Additional keyword arguments are always accepted and passed to the endpoint - TD DataSchema objects don't distinguish whether extra properties are allowed or not.
    • The output schema is converted to a return type hint
    • The function body calls invoke_action.
    • ... is used to distinguish between explicitly set None values, and unspecified values (i.e. not included in the JSON). This allows the server to fill in default values, which is safer than trying to generate default values in the Python code.
  • ast is used to generate a syntax tree that's then turned into code. This should ensure the generated code is valid. However, we do need to take care, as it does not ensure that names are legal Python names. I've wrapped the relevant ast functions to validate the names. Happily, string escaping does seem to be robus without any extra help.

Schema conversion

Conversion from DataSchema to Python types is implemented, and can generate client types for everything in the current OFM simulation. Julian's more recent PR (#300) independently implemented very similar logic, which I take as a good sign.

Types are converted recursively, with support for:

  • integer -> int
  • number -> float
  • boolean -> bool
  • string -> str
  • anyOf -> Union
  • null -> None
  • array -> list (if an item type is specified, it's converted recursively) or tuple (if several item types are specified)
  • object -> dict[str, Any] or a generated pydantic.BaseModel subclass (if properties are specified)
  • Anything else -> Any

object schemas will be recursively converted to pydantic models. This can be turned off by disabling recursion, and more fine-grained control may be helpful.

Key differences from #300 are:

  • array schemas are converted to tuples if items is an array of Data Schema objects, as per JSONSchema 2019 (there's a link in the relevant comment in DataSchemaConverter.convert().
  • object schemas are converted to dynamically-generated pydantic.BaseModel subclasses, if they specify properties. If properties are not specified, object is still rendered as dict.
  • By default, this implementation is recursive, and will nest up to ten levels of type conversion. This may be increased or decreased by passing an argument to the constructor of DataSchemaConverter (though that's not yet exposed in e.g. ThingClient.from_url().

Security

ast.Name() does not ensure that the string passed in is a legal Python name. Instead, the string seems to be unparse-ed verbatim. I've added a function to validate names and used it to validate all the names that are passed in from the TD. I've checked this manually, but this should be checked by the reviewer.

Still to do

Before this can be merged, we need to add a few things:

  • More testing, including all the data types
  • Actual use of the created class. This is done, because ThingClient.from_url now uses this module.
  • Better deduplication of models.
  • Consider how to expose (or not generate) models when returning only a client object, e.g. in ThingClient.from_url.
  • Recognition of Blob in the output (rather than autogenerating a model for it).
  • Expose controls for recursion and/or model generation in ThingClient.from_url so we can revert to something closer to the current client if that's desired.
  • It would be nice to check that the methods/properties of the generated client class match the Thing Description of the thing we're connecting to. This may be left for the future.

Future work

In a subsequent PR, it would be very good to:

  • Allow import of some input/output types, so we can re-use existing models rather than autogenerate copies.
  • Process values that come from the server, as a means of "reinflating" them to Python objects (particularly useful for np.array). This probably uses pydantic validation, probably with an option to skip it if needed.
  • Make it possible to wrap a Thing (analogous to DirectThingClient) to ease the transition between client-side and server-side code.

@VigneshVSV

VigneshVSV commented Dec 4, 2024 •

Copy link
Copy Markdown

I remember us talking about this. Now that I am somewhat finished with my obligations, I will have deeper look at the latest changes in labthings.

FYI, I already released pydantic based property types from this code base as part of my repository.

@rwb27 rwb27 added this to the v0.0.12 milestone Jul 31, 2025
@rwb27 rwb27 changed the title Draft: Code generation for ThingClient subclasses Code generation for ThingClient subclasses Jul 31, 2025
@rwb27
rwb27 marked this pull request as draft July 31, 2025 08:37
@rwb27 rwb27 modified the milestones: v0.0.12, v0.0.13 Nov 14, 2025
@rwb27

rwb27 commented Nov 14, 2025

Copy link
Copy Markdown
Collaborator Author

I'm going to bump this to 0.0.13 as it's not yet critical. I am keen to get in in though, as it will really improve the experience of using lab things from e.g. a python notebook.

@rwb27 rwb27 modified the milestones: v0.1.0, v0.1.1, v0.2.0 Mar 3, 2026
@rwb27 rwb27 modified the milestones: v0.2.0, v0.3.0 Apr 2, 2026
@rwb27
rwb27 force-pushed the client-code-generation branch 2 times, most recently from bff6809 to 4a46348 Compare June 9, 2026 14:11
@barecheck

barecheck Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Barecheck - Code coverage report

Total: 96.28%

Your code coverage diff: -1.14% ▾

Uncovered files and lines
FileLines
src/labthings_fastapi/base_descriptor.py181, 195-196
src/labthings_fastapi/client/__init__.py44, 80, 83-84, 242, 292-295, 409
src/labthings_fastapi/code_generation.py42-43, 106, 170, 184, 216, 339, 343, 363-364, 371, 373, 388, 390, 394, 418-419, 438-440, 513, 518-519, 534, 536, 647, 651, 746, 749, 774-775, 807-815, 818-819, 823, 828, 833-834

@rwb27

rwb27 commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator Author

I think this is now sufficiently close to complete that it's better than the existing ThingClient implementation.

The unpinned tests are failing because of a new Ruff rule, this should be fixed separately (and I'm trying not to establish a precedent that upstream changes hold up merge requests if the pinned tests are passing).

The OFM test failure is, I believe, a bug in the OFM test that's uncovered by these changes, it should be a trivial fix in a feature branch.

I'm very aware this needs a lot more test code, and I'd be very grateful for advice from @bprobert97 on how to do that. I think what I really want is a way to randomly construct challenging type hints, but I think that would be a pig to implement, unless hypothesis is very much cleverer than I guessed.

For a first pass of review, I think I'm mostly hoping for feedback on:

  1. Is code generation using ast from the Thing Description safe? I think it's OK; unless there's a bug in ast.unparse there's no way to achieve code execution from any string passed in from the Thing Description.
  2. Is writing to a temporary file and loading it as a module a reasonable way to dynamically generate a subclass? It would also be possible to use eval, I don't think there's a huge change in safety but it would break the current implementation of properties, and potentially stop some documentation tools from picking up their docstrings (as this is commonly done by inspecting the source, which you can't do for modules created with eval).

I can't pretend I don't have an opinion here - I like this implementation. However, I'm also aware this sort of code generation needs a lot of care, and I do want to get it right.

@rwb27

rwb27 commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator Author

For the record, I've also run the generated code for the microscope client through pdoc and at first glance the docs look really pretty nice.

@rwb27 rwb27 modified the milestones: v0.3.0, v0.4.0 Jun 15, 2026
@bprobert97

Copy link
Copy Markdown
Contributor

I like this! Moving from dynamic type() or eval() calls to an AST-based generation approach is significantly more robust and makes the resulting client classes much easier to debug.

I've only looked at code_generation.py and test_client_generation.py Here are a few thoughts on your questions:

  1. Is AST-based Code Generation Safe?

Yes, but watch out for runtime crashes. Using the ast module is inherently safer than string concatenation because it strictly enforces Python's grammar. You cannot achieve arbitrary code execution via an injection attack through ast.unparse(if a malicious Thing Description (TD) includes a payload, wrapping that in ast.Name(id=...) will safely unparse it as a literal string or raise an AST validation error rather than executing it).

While it's safe from execution, it isn't safe from crashing the server. If a TD contains an affordance titled "1st Sensor", your title_to_snake_case function will output 1st_sensor. Passing "1st_sensor" to ast.Name compiles fine, but when spec.loader.exec_module(module) runs, Python will throw a SyntaxError because variables cannot start with a number.

You might want to add a quick sanitisation step to ensure generated strings are strictly valid Python identifiers, unless this is validated elsewhere?

  1. Is writing to a temporary file and loading it as a module a reasonable way to dynamically generate a subclass?

The temporary file approach could be the right way to go. Tracebacks pointing to actual line numbers are invaluable. But you are right about the documentation tools potentially breaking. If we want a persistent source, we could write these files to a persistent cache directory instead?

I'm very aware this needs a lot more test code, and I'd be very grateful for advice from @bprobert97 on how to do that.

I think hypothesis is a good tool to use for this! You can use Hypothesis's st.recursive and st.builds strategies to easily generate heavily nested DataSchema objects.

Recursive: https://hypothesis.readthedocs.io/en/latest/reference/strategies.html#hypothesis.strategies.builds
Builds: https://hypothesis.readthedocs.io/en/latest/reference/strategies.html#hypothesis.strategies.builds

As an example:

from hypothesis import given, strategies as st
from labthings_fastapi.thing_description._model import DataSchema, Type

# 1. Build a strategy for simple, flat schemas
simple_schema = st.builds(
    DataSchema, 
    type=st.sampled_from([Type.string, Type.integer, Type.boolean, Type.number])
)

# 2. Recursively generate arrays or nested object schemas
nested_schema = st.recursive(
    simple_schema,
    lambda children: st.one_of(
        # Arrays of items
        st.builds(DataSchema, type=st.just(Type.array), items=children),
        # Objects with properties
        st.builds(DataSchema, type=st.just(Type.object), properties=st.dictionaries(st.text(min_size=1), children))
    ),
    max_leaves=5
)

@given(nested_schema)
def test_schema_conversion(schema):
    converter = DataSchemaConverter()
    # The test simply asserts that the converter can handle the wildly nested 
    # schema without raising unexpected exceptions
    result = converter.convert(schema)
    assert result is not None

@rwb27
rwb27 force-pushed the client-code-generation branch from 71394cd to c338c3b Compare June 30, 2026 12:52
@rwb27
rwb27 force-pushed the client-code-generation branch from a6bc075 to 88bbfff Compare November 17, 2026 23:21
This generates Python code for a module containing a client.
The Python code generated for the test thing executes successfully, though
the name of the class is not quite right yet.
Dataschemas of type Object that have defined properties are now
converted to Pydantic models.

This should allow much better autocompletion.

The inconsistency of using `dict[str, any]` as a fallback rankles, but I think it's the best option.
This should be significantly more secure: I believe it should now be
impossible for a malcious Thing Description to create dangerous Python code.

In doing this, I've simplified the way the client creates properties - I need
to check if it type hints them correctly.

There are still a few things to fix:
* Default values probably want to be `...` rather than constants, so they're
  filled in server-side.
* This doesn't yet validate/convert return values.
* This isn't tested enough and probably doesn't actually work!
* We need configurability: as a minimum, recursion limits and fallback to
  `Any` so it fails gracefully if given a bad TD.
This commit adds:
* a limit on recursion
* a bunch of tidying up
* many more comments
* cleaner generated code
* generated docstrings for actions, properties, and Things.
* thing client properties now derive from BaseDescriptor - this required a few changes, but makes the generated code neater.
* BaseDescriptor may now be defined on non-Thing classes.
This moves the single file out of the folder, keeping the module name the same.

I've also provided the `type_params` argument on Python > 3.11.
This compares unparsed strings rather than AST nodes, as the latter
don't properly show as equal.
`ast.compare` will help here, but not
until we drop a few Python versions.
One-line docstrings end up in both the `title` and `description` fields.
We now deduplicate this, so the generated docstrings match the
originals.
This executes `ruff` in a subprocess, which `ruff` flags as potentially insecure.
I've thought through this carefully and I'm happy we can ignore the
warning, as I don't see any opportunity
to inject malicious input.
The code mapping JSONSchema to types had a warning by default when
it typed anything as `Any`.
I have softened this, so now it is happy to use `Any` for types that
have a sufficiently vague schema (i.e.
no type, oneof, const or enum).
This adds tests for illegal names and string quoting.

Sadly, `ast.Name` does not verify the supplied string is a valid Python name.
I've written a conservative regex to do this, and added tests.

I've checked through for every instance of a `str` being passed to code generation
functions and added an `assert_legal_name` to check it.

This should keep us safe, but I'll need to leave instructions to the code reviewer
about checking for strings leaking through as names: it's not just
`ast.Name` that I'm worried about - class
definitions and so on also accept strings.

I've also fixed an incorrect type in ThingClient.
@rwb27
rwb27 force-pushed the client-code-generation branch from 88bbfff to 112a3be Compare November 18, 2026 15:11
I've added another case and another parametrized run to deal with two untested cases I identified.
ast.ClassDef and ast.FunctionDef take an extra argument between 3.11 and 3.12.
However, testing suggests I can just leave it out with no ill effects.
I'll remove the if statement and the test, but I'll reinstate them if something fails
down the line.
It turns out I can just use the Python 3.11 form of ast.ClassDef and ast.FunctionDef,
and mypy does not error on 3.11 or 3.13.
This does not yet test the creation of models. It mostly tests against
`type_to_dataschema` in order to
keep the test case definitions succinct.
I ran `mccabe` and it flagged `convert` as too complex so I've split it up a bit.

This structure splits out converter functions for specific types.
The schema is passed to each function in turn, and the first function to return a
non-None value gets used.

This replaces the very long `elif` block with a for loop. I hope it's clearer as well as
making the linter happier.
@rwb27

rwb27 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Having now tested it, I am sad to report that ast.Name("!illegal!") happily generates an ast expression that unparses to !illegal!.

I've written a function that ensures all strings passed to ast.Name are valid Python identifiers. It also checks for reserved words and blocks them.

Currently it is possible to generate a model that shadows a builtin: I think that's probably better dealt with in the name-generation code (which already checks for clashes with other generated names) rather than in my _name wrapper.

This will definitely want attention at code review.

@rwb27

rwb27 commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

I have been thinking more about how to handle object types. Currently, if we have an object it means that the value is either typed as a dict or a BaseModel. The current code will turn dict into dict (without subscripts) and BaseModel into BaseModel (though not the same BaseModel subclass - just one with the same attributes.

  • ✅ Advantage: the code looks the same on client- and server-side.
  • ❌ Disadvantage: setting properties or providing action inputs requires you to create a model instance, and you may not have the model in your namespace.
  •   from my_generated_client import MyThingClient, MyActionInput
      
      client = MyThingClient.from_url("http://localhost:5000/")
      client.my_action(a=MyActionInput(foo="bar"))

A tempting alternative is to use a TypedDict.

  • ✅ This can work with pydantic to provide validation via a RootModel or TypeAdapter.
  • ✅ Most autocompletion and introspection tools understand it so you get autocompletion and documentation of the required keys and types.
  • ✅ It still type checks with MyPy.
  • ✅ You don't have to instantiate, or import, a model.
  •   from my_generated_client import MyThingClient
      
      client = MyThingClient.from_url("http://localhost:5000/")
      client.my_action(a={"foo": "bar"})
  • ❌ The signature doesn't match the server.
  • ❌ Not all tools will preserve descriptions of each key in their documentation - models definitely do this better.

I am curious to hear opinions. I worry that I'm excited about TypedDict as a language feature and that's making me do something inadvisable. However, I do think it's a nice compromise between making lots of models, and dealing with lots of unstructured dicts.

It would absolutely be possible to define __getitem__ and friends on a subclass of BaseModel. That would allow a Thing to return a model, type hinted correctly, but still be compatible with code that expects a dictionary. It wouldn't be full parity between server and client, but it would mean code developed client-side still ran happily on the server. This could even be retro-fitted to existing Things with a wrapper class, like a less annoying version of DirectThingClient.

This checks tuples as well as lists, as the increment in recursion depth happens separately.
@rwb27

rwb27 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

After a bit more thinking, I'm inclined to split up this PR.

I think this PR should include only:

  • Add the code generation module, with the ability to generate a ThingClient subclass in a Python module.
  • Use the new module to replace the dynamic signature-manipulation code in ThingClient.subclass_from_thing_description
  • Unit testing for the new functionaily.
  • Correct conversion of simple types (scalar datatypes, lists, tuples) but render object as dict without any dynamic model generation.

I will then open two more PRs:

  • Recursive conversion of object DataSchemas to pydantic models or, more likely, TypedDict subclasses.
  • Communication of Python type hints as part of the DataSchema generated by a Thing, so the types on the server and client match.

I think this provides the smoothest transition from current to new behaviour. Swapping the current behaviour (where everything's a dictionary) for use of TypedDict would have almost no effect at runtime, but would all of a sudden allow much better type hinting and autocompletion of client code. Enabling a Thing Description to reference Python types is then a nicer mechanism to make sure Blob and np.ndarray are properly handled.

Splitting like this also means I'll be able to get this PR tested and approved much more easily, and should avoid reviewers having to deal with a bunch of changes all at once.

This commit does two things:

1. It remove recursive creation of BaseModel subclasses to describe types. `object` DataSchemas are now just converted to `dict`.
2. `generate_client_ast` is now split up, moving code that generates properties
and actions into two separate functions for easier testing (and reading).

(1) is the behaviour of the current dynamic ThingClient, so it should smooth
the upgrade path as well as streamlining this PR.
This sorts imports, and allows use of a Path to specify the destination.
This checks that generating a client module produces the expected file.
The created module is normalised with `ruff format` to account for version-dependence in `ast.unparse`.

I've also expanded the testing of the case conversion functions to cover everything
that was included in test_client_generation.py.

I've added a few tests of error/edge cases that don't get hit by the round-trip tests
or the test that generates a whole client.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants